//
//  ClientMainViewController.m
//  aigo
//
//  Created by Tai Truong on 11/20/12.
//  Copyright (c) 2012 AIGO. All rights reserved.
//

#import "ClientMainViewController.h"
#import "AppViewController.h"
#import "PersonDataManager.h"

@interface ClientMainViewController ()
@end

@implementation ClientMainViewController
{
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _APIRequester = [APIRequester new];
        _APIRequesterAutomation = [APIRequester new];
        _isRequestAtFirstTime = YES;
    }
    return self;
}

- (void)initInterface {
    // Touched Gesture
    _touchedGestureRecognizer = [TouchedGestureRecognizer new];
    _touchedGestureRecognizer.delegateCallBack = self;
    [_mapViewClient addGestureRecognizer:_touchedGestureRecognizer];
    
    _mapViewClient.showsUserLocation = YES;
    
    
    // Popup
    _viewListPopup.frame = CGRectMake(0, HEIGHT_STATUS_BAR, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR);
    [[AppViewController Shared].navigationController.view addSubview:_viewListPopup];
    _viewListPopup.hidden = YES;
    
    // Driver Interface
    _viewDriverInterface.hidden = YES;
    
    
    // Map Interface
    _viewMapInterface.frame = CGRectMake(_viewDistanceInterface.frame.origin.x, _viewDistanceInterface.frame.origin.y, _viewMapInterface.frame.size.width, _viewMapInterface.frame.size.height + _viewDistanceInterface.frame.size.height + _viewDriverInterface.frame.size.height);
    
    [self loadSeatsInterfaceWithSeatsStatus:enumClientSeatsStatus_All];
    
    // Frames
    _frameListButton1 = _btnRequestClosestDriver.frame;
    _frameListButton2 = _btnRequestThisDriver.frame;
    _frameListButton3 = _btnCancelTheRequest.frame;
    _frameListButton4 = _btnCallYourDriver.frame;
    _frameListButton5 = _btnCancelThisTransaction.frame;
    
//    // Region
//    MKCoordinateRegion newRegion;
//    newRegion.center.latitude = [UserDataManager Shared].userLocation.coordinate.latitude;
//    newRegion.center.longitude = [UserDataManager Shared].userLocation.coordinate.longitude;
//    newRegion.span.latitudeDelta = _mapViewClient.region.span.latitudeDelta;
//    newRegion.span.longitudeDelta = _mapViewClient.region.span.longitudeDelta;
//    [_mapViewClient setRegion:newRegion animated:NO];
    
    // calculate central point of kards
    MKCoordinateRegion region = [self createZoomRegionFromCentralPointAndRadius :[PersonDataManager clientShared].categoryArray];
    
    // Zoom and scale to central point
    [_mapViewClient setRegion:region animated:TRUE];
    [_mapViewClient regionThatFits:region];
    [_mapViewClient reloadInputViews];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Init
    [self initInterface];
    
    // Load DATA
    [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER];
}

- (void)viewDidUnload
{
    [self setBtnFinishTrip:nil];
    [self setViewMapInterface:nil];
    [self setViewDistanceInterface:nil];
    [self setBtn4Seats:nil];
    [self setBtn8Seats:nil];
    [self setViewDriverInterface:nil];
    [self setLblDriverCapacity:nil];
    [self setLblDriverLicense:nil];
    [self setLblDriverVendor:nil];
    [self setLblDriverName:nil];
    [self setBtnCancelThisTransaction:nil];
    [self setBtnCallYourDriver:nil];
    [self setBtnCancelTheRequest:nil];
    [self setBtnRequestThisDriver:nil];
    [self setBtnRequestClosestDriver:nil];
    [self setViewListPopup:nil];
    [self setLblClientAddress:nil];
    [self setMapViewClient:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)loadInterface {
    NSArray *oldAnnotations = _mapViewClient.annotations;
    for (id<MKAnnotation> annotation in oldAnnotations) {
        if (![annotation isKindOfClass:[MKUserLocation class]]) {
            [_mapViewClient removeAnnotation:annotation];
        }
    }
    
    [_mapViewClient addAnnotations:[PersonDataManager clientShared].categoryArray];
    
    NSDictionary *dic = [UserDataManager Shared].currentPlaceMark.addressDictionary;
    NSString *addLine = [[dic valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
    
    _lblClientAddress.text = addLine;
    [_lblClientAddress setMinimumFontSize:FONT_SIZE_KARD_LABEL_MINIMUM];
    _lblClientAddress.adjustsFontSizeToFitWidth = YES;
    
//    // calculate central point of kards
//    MKCoordinateRegion region = [self createZoomRegionFromCentralPointAndRadius :[PersonDataManager clientShared].categoryArray];
//    
//    // Zoom and scale to central point
//    [_mapViewClient setRegion:region animated:TRUE];
//    [_mapViewClient regionThatFits:region];
//    [_mapViewClient reloadInputViews];
    
}

#pragma mark - Private procedures

- (void)calculateCentralPointAndRadiusFromLocationKards:(NSMutableArray*) categoryArray withCurrenLocation:(BOOL)bCurrentLocation {
    
    // Find latitude and longtitude smallest and biggest
    float smallLongtitute   = 0;
    float smallLattitute    = 0;
    float bigLongtitute     = 0;
    float bigLattitute      = 0;
    
    // include current location in calculate
    if (bCurrentLocation) {
        smallLongtitute   = [UserDataManager Shared].userLocation.coordinate.longitude;
        smallLattitute    = [UserDataManager Shared].userLocation.coordinate.latitude;
        bigLongtitute     = [UserDataManager Shared].userLocation.coordinate.longitude;
        bigLattitute      = [UserDataManager Shared].userLocation.coordinate.latitude;
    }
    
    for (PersonNodeData *kardNodeData in categoryArray) {
        //NSLog(@"-caluclateCentralPointWithLocationKards-latitude=%f---longtitude=%f",kardNodeData.coordinate.latitude, kardNodeData.coordinate.longitude);
        if (kardNodeData.coordinate.latitude < smallLattitute || smallLattitute == 0) {
            smallLattitute = kardNodeData.coordinate.latitude;
        }
        if (kardNodeData.coordinate.latitude > bigLattitute || bigLattitute == 0) {
            bigLattitute = kardNodeData.coordinate.latitude;
        }
        if (kardNodeData.coordinate.longitude < smallLongtitute || smallLongtitute == 0) {
            smallLongtitute = kardNodeData.coordinate.longitude;
        }
        if (kardNodeData.coordinate.longitude > bigLongtitute || bigLongtitute == 0) {
            bigLongtitute = kardNodeData.coordinate.longitude;
        }
    }
    
    // Update central point
    _centralPoint.latitude    = (bigLattitute + smallLattitute)/2;
    _centralPoint.longitude   = (bigLongtitute + smallLongtitute)/2;
    
    NSLog(@"-caluclateCentralPointWithLocationKards-central point - latitude=%f---longtitude=%f",_centralPoint.latitude, _centralPoint.longitude);
    
    // Calculate radius
    CLLocation *marklocation = [[CLLocation alloc] initWithLatitude:smallLattitute longitude:smallLongtitute];
    CLLocation *centralLocation = [[CLLocation alloc] initWithLatitude:_centralPoint.latitude longitude:_centralPoint.longitude];
    
    _radiusMeters = ([marklocation distanceFromLocation:centralLocation]);
    
    if (_radiusMeters == 0) {
        // Default for radius is 1km
        //Too far is when you show the entire USA.  Too close is when you show only a 300 ft/100m radius.
        //I think we can settle on something in the middle.  How about something like a 1Km radius
        _radiusMeters = 1000;
    }
    NSLog(@"Distance in meters: %f", _radiusMeters);
    
}

- (MKCoordinateRegion)createZoomRegionFromCentralPointAndRadius:(NSMutableArray*) categoryArray {
    
    [self calculateCentralPointAndRadiusFromLocationKards:categoryArray withCurrenLocation:YES];
    
    
     // Check if current location is too far Kards to recalculate with not location
     if (_radiusMeters > MAXIMUM_SCALEABLE_RADIUS_METERS) {
     [self calculateCentralPointAndRadiusFromLocationKards:categoryArray withCurrenLocation:NO];
     }
     
    
    // have no deal zoom minimum scale to current location
    if ([categoryArray count] == 0 || _radiusMeters > MAXIMUM_SCALEABLE_RADIUS_METERS/2) {
        _radiusMeters = MAXIMUM_SCALEABLE_RADIUS_METERS/2;
        _centralPoint.latitude = [UserDataManager Shared].userLocation.coordinate.latitude;
        _centralPoint.longitude =[UserDataManager Shared].userLocation.coordinate.longitude;
    }
    return MKCoordinateRegionMakeWithDistance(_centralPoint, _radiusMeters*2, _radiusMeters*2   );
    
}


- (void)loadPopupInterface {
    _btnRequestClosestDriver.hidden = YES;
    _btnRequestThisDriver.hidden = YES;
    _btnCancelTheRequest.hidden = YES;
    _btnCancelThisTransaction.hidden = YES;
    _btnCallYourDriver.hidden = YES;
    _btnFinishTrip.hidden = YES;
    
    if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_Invalid) {
        _btnRequestClosestDriver.hidden = NO;
        _btnRequestClosestDriver.frame = _frameListButton1;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_PickUpThisDriver) {
        _btnRequestClosestDriver.hidden = NO;
        _btnRequestClosestDriver.frame = _frameListButton1;
        
        _btnRequestThisDriver.hidden = NO;
        _btnRequestThisDriver.frame = _frameListButton2;
        
        _btnCallYourDriver.hidden = NO;
        _btnCallYourDriver.frame = _frameListButton3;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_RequestThisDriver) {
        _btnCallYourDriver.hidden = NO;
        _btnCallYourDriver.frame = _frameListButton1;
        
        _btnCancelTheRequest.hidden = NO;
        _btnCancelTheRequest.frame = _frameListButton2;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_RequestClosestDriver) {
        _btnCancelTheRequest.hidden = NO;
        _btnCancelTheRequest.frame = _frameListButton1;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_WaitingForDriverArrival) {
        _btnCallYourDriver.hidden = NO;
        _btnCallYourDriver.frame = _frameListButton1;
        
        _btnCancelThisTransaction.hidden = NO;
        _btnCancelThisTransaction.frame = _frameListButton2;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_GettingCar) {
        _btnCallYourDriver.hidden = NO;
        _btnCallYourDriver.frame = _frameListButton1;
        
        _btnCancelThisTransaction.hidden = NO;
        _btnCancelThisTransaction.frame = _frameListButton2;
    }
    else if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_FinishTrip) {
        _btnFinishTrip.hidden = NO;
        _btnFinishTrip.frame = _frameListButton1;
        
        _btnCallYourDriver.hidden = NO;
        _btnCallYourDriver.frame = _frameListButton2;
        
        _btnCancelThisTransaction.hidden = NO;
        _btnCancelThisTransaction.frame = _frameListButton3;
    }
}

- (void)loadSeatsInterfaceWithSeatsStatus:(enumClientSeatsStatus)seats {
    if (seats == enumClientSeatsStatus_Invalid || seats == enumClientSeatsStatus_All) {
        _btn4Seats.selected = NO;
        _btn8Seats.selected = NO;
    }
    else if (seats == enumClientSeatsStatus_4Seats) {
        _btn4Seats.selected = YES;
        _btn8Seats.selected = NO;
    }
    else if (seats == enumClientSeatsStatus_8Seats) {
        _btn4Seats.selected = NO;
        _btn8Seats.selected = YES;
    }
    
    _seatsStatus = seats;
}

- (void)loadDriverInterfaceWithNodeData:(PersonNodeData *)node {
    if (node) {
        if (_viewDistanceInterface.frame.origin.y == _viewMapInterface.frame.origin.y) {
            CATransition *animation = [CATransition animation];
            [animation setDuration:TIMER_CHANGING_VIEW];
            [animation setType:kCATransitionFade];
            [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
            _viewMapInterface.frame = CGRectMake(_viewDistanceInterface.frame.origin.x, _viewDistanceInterface.frame.origin.y + _viewDistanceInterface.frame.size.height, _viewMapInterface.frame.size.width, _viewMapInterface.frame.size.height - _viewDistanceInterface.frame.size.height -_viewDriverInterface.frame.size.height);
            [[_viewMapInterface layer] addAnimation:animation forKey:@"animation"];
        }
        
        _viewDriverInterface.hidden = NO;
        
        _lblDriverName.text = node.personName;
        [_lblDriverName setMinimumFontSize:FONT_SIZE_KARD_LABEL_MINIMUM];
        _lblDriverName.adjustsFontSizeToFitWidth = YES;
        
        _lblDriverVendor.text = [NSString stringWithFormat:@"Vendor: %@", node.driverVendor];
        [_lblDriverVendor setMinimumFontSize:FONT_SIZE_KARD_LABEL_MINIMUM];
        _lblDriverVendor.adjustsFontSizeToFitWidth = YES;
        
        _lblDriverLicense.text = [NSString stringWithFormat:@"License No. %@", node.driverLicense];
        [_lblDriverLicense setMinimumFontSize:FONT_SIZE_KARD_LABEL_MINIMUM];
        _lblDriverLicense.adjustsFontSizeToFitWidth = YES;
        
        _lblDriverCapacity.text = [NSString stringWithFormat:@"Capacity: %@", node.driverCapacity];
        [_lblDriverCapacity setMinimumFontSize:FONT_SIZE_KARD_LABEL_MINIMUM];
        _lblDriverCapacity.adjustsFontSizeToFitWidth = YES;
        
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_PickUpThisDriver;
    }
    else {
        if (_viewDistanceInterface.frame.origin.y < _viewMapInterface.frame.origin.y) {
            CATransition *animation = [CATransition animation];
            [animation setDuration:TIMER_CHANGING_VIEW];
            [animation setType:kCATransitionFade];
            [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
            _viewMapInterface.frame = CGRectMake(_viewDistanceInterface.frame.origin.x, _viewDistanceInterface.frame.origin.y, _viewMapInterface.frame.size.width, _viewMapInterface.frame.size.height + _viewDistanceInterface.frame.size.height + _viewDriverInterface.frame.size.height);
            [[_viewMapInterface layer] addAnimation:animation forKey:@"animation"];
        }
        
        _viewDriverInterface.hidden = YES;
    }
    
    [[UserDataManager Shared] save];
}

- (void)update {
    if ([ASIHTTPRequest isNetworkReachable]) {
        if (CFAbsoluteTimeGetCurrent() - _updateDriverTimer > TIMER_AUTOMATION_UPDATE_CLIENT && [UserDataManager Shared].userRequestStatus != enumClientMainStatus_PickUpThisDriver) {
            _updateDriverTimer = CFAbsoluteTimeGetCurrent();
            [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER];
        }
    }
}

#pragma mark - Actions

- (IBAction)touchUpInsideSetting:(id)sender {
    [[AppViewController Shared] changeToProfileSetting];
}

- (IBAction)touchUpInsideList:(id)sender {    
    CATransition *animation = [CATransition animation];
    [animation setDuration:TIMER_CHANGING_VIEW];
    [animation setType:kCATransitionFade];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    _viewListPopup.hidden = NO;
    [[_viewListPopup layer] addAnimation:animation forKey:@"animation"];
    
    [self loadPopupInterface];
}

- (IBAction)touchUpInsideHideList:(id)sender {
    CATransition *animation = [CATransition animation];
    [animation setDuration:TIMER_CHANGING_VIEW];
    [animation setType:kCATransitionFade];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    _viewListPopup.hidden = YES;
    [[_viewListPopup layer] addAnimation:animation forKey:@"animation"];
}

- (IBAction)touchUpInsideSeatsButton:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn == _btn4Seats) {
        if (btn.selected) {
            [self loadSeatsInterfaceWithSeatsStatus:enumClientSeatsStatus_All];
        }
        else {
            [self loadSeatsInterfaceWithSeatsStatus:enumClientSeatsStatus_4Seats];
        }
    }
    else if (btn == _btn8Seats) {
        if (btn.selected) {
            [self loadSeatsInterfaceWithSeatsStatus:enumClientSeatsStatus_All];
        }
        else {
            [self loadSeatsInterfaceWithSeatsStatus:enumClientSeatsStatus_8Seats];
        }
    }
    
    [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER];
}

- (IBAction)touchUpInsideListButton:(id)sender {
    [[AppViewController Shared] hidePopupWithNotificationType:enumRemoveNotificationType_Invalid];
    
    //    btn.selected = !btn.selected;
    UIButton *btn = (UIButton *)sender;
    if (btn == _btnRequestClosestDriver) {
        [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_CLOSEST_DRIVER];
    }
    else if (btn == _btnRequestThisDriver) {
        [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_THIS_DRIVER];
    }
    else if (btn == _btnCancelTheRequest) {
        [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_CANCEL_THE_REQUEST];
    }
    else if (btn == _btnCancelThisTransaction) {
        [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_CANCEL_THIS_TRANSACTION];
    }
    else if (btn == _btnCallYourDriver) {
        
    }
    else if (btn == _btnFinishTrip) {
        if (_selectedDriver) {
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_PickUpThisDriver;
        }
        else {
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
        }
        [[UserDataManager Shared] save];
    }
    
    [self touchUpInsideHideList:nil];
}

#pragma mark - APIRequesterProtocol

- (void)requestAPIWithType:(ENUM_API_REQUEST_TYPE)type {
    if (type == ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER) {
        int seatsNum = 0;
        if (_seatsStatus == enumClientSeatsStatus_4Seats) {
            seatsNum = 4;
        }
        else if (_seatsStatus == enumClientSeatsStatus_8Seats) {
            seatsNum = 8;
        }
        
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        [params setObject:[NSString stringWithFormat:@"%i", INT_CLIENT_PAGE_SIZE_INDEX] forKey:STRING_REQUEST_KEY_NUMBER];
        [params setObject:[NSString stringWithFormat:@"%i", seatsNum] forKey:STRING_REQUEST_KEY_SEAT];
        
        if ([PersonDataManager clientShared].categoryArray.count == 0 && _isRequestAtFirstTime == YES) {
            [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        }
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_CLOSEST_DRIVER, [UserDataManager Shared].userID];
        
        [_APIRequesterAutomation requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
    }
    else if (type == ENUM_API_REQUEST_TYPE_USER_LOGOUT) {
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        // TrongV 2012/11/21
        [params setObject:[AppViewController Shared].configDataModel.deviceToken forKey:STRING_REQUEST_KEY_DEVICE_TOKEN];
        
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, 0, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR)];
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_USER_LOGOUT, [UserDataManager Shared].userID];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_CLOSEST_DRIVER) {
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        [params setObject:[NSString stringWithFormat:@"%f,%f", [UserDataManager Shared].userLocation.coordinate.latitude, [UserDataManager Shared].userLocation.coordinate.longitude] forKey:STRING_REQUEST_KEY_LOC];
        
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        
        // HARD CODE:
//        NSString *userIdDriver = @"50d83872e739b0dd1a000004";
        NSString *userIdDriver = [UserDataManager Shared].userID;
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_REQUEST_CLOSEST_DRIVER, userIdDriver];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
        
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_RequestClosestDriver;
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_THIS_DRIVER && _selectedDriver) {
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        [params setObject:[UserDataManager Shared].selectedPersonID forKey:STRING_REQUEST_KEY_DRIVER_ID];
        
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        
        NSString *userIdDriver = [UserDataManager Shared].userID;
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_REQUEST_THIS_DRIVER, userIdDriver];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
        
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_RequestThisDriver;
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_CANCEL_THE_REQUEST) {
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        
        NSString *userIdDriver = [UserDataManager Shared].userID;
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_CANCEL_THE_REQUEST, userIdDriver];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:nil andDelegate:self];
        
        if (_selectedDriver) {
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_PickUpThisDriver;
        }
        else {
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
        }
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_CANCEL_THIS_TRANSACTION && [UserDataManager Shared].selectedPersonID) {
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        [params setObject:[UserDataManager Shared].selectedPersonID forKey:STRING_REQUEST_KEY_DRIVER_ID];
        
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        
        NSString *userIdDriver = [UserDataManager Shared].userID;
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_CANCEL_THIS_TRANSACTION, userIdDriver];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
        
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_CHARGE_BILL && _remoteNotification) {
        NSMutableDictionary  *params = [NSMutableDictionary new];
        
        [params setObject:[_remoteNotification objectForKey:STRING_RESPONSE_KEY_DRIVER_ID] forKey:STRING_REQUEST_KEY_DRIVER_ID];
        [params setObject:[_remoteNotification objectForKey:STRING_RESPONSE_KEY_PRICE] forKey:STRING_REQUEST_KEY_PRICE];
        
        [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, HEIGHT_HOME_VIEW_CONTROLLER_TITLE, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight] - HEIGHT_STATUS_BAR - HEIGHT_HOME_VIEW_CONTROLLER_TITLE)];
        
        NSString *userIdDriver = [UserDataManager Shared].userID;
        
        NSString *strURL = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_CLIENT_CHARGE_BILL, userIdDriver];
        
        [_APIRequester requestWithType:type andRootURL:strURL andPostMethodKind:YES andParams:params andDelegate:self];
        
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_FinishTrip;
    }
    
    _isRequestAtFirstTime = NO;
    [[UserDataManager Shared] save];
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    if (type != ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER) {
        NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
    }
    
    if ([UserDataManager Shared].userRequestStatus != enumClientMainStatus_RequestThisDriver && [UserDataManager Shared].userRequestStatus != enumClientMainStatus_RequestClosestDriver) {
        [[AppViewController Shared] isRequesting:NO andRequestType:type andFrame:CGRectZero];
    }
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_MSG]);
        return;
    }
    
    if (type == ENUM_API_REQUEST_TYPE_USER_LOGOUT) {
        [UserDataManager Shared].sessionID = @"";
        [UserDataManager Shared].loginStatus = NO;
        [[UserDataManager Shared] save];
        [[AppViewController Shared] changeBackToWelcome];
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_CLOSEST_DRIVER || type == ENUM_API_REQUEST_TYPE_CLIENT_REQUEST_THIS_DRIVER) {
        
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_GET_CLOSEST_DRIVER) {
        NSMutableDictionary *dicJson = [sbJSON objectWithString:[request responseString] error:&error];
        NSMutableArray *results = [dicJson objectForKey:STRING_RESPONSE_KEY_RESULTS];
        
        [[PersonDataManager clientShared] resetAllData];
        if (results.count > 0) {
            for (NSMutableDictionary *nodeDic in results) {
                NSMutableDictionary *obj = [nodeDic objectForKey:STRING_RESPONSE_KEY_OBJ];
                
                PersonNodeData *node = [[PersonNodeData alloc] initWithPersonName:[obj objectForKey:STRING_RESPONSE_KEY_NAME] andPersonID:[obj objectForKey:STRING_RESPONSE_KEY__ID] andPersonSmallAvatar:nil];
                node.titletext = [obj objectForKey:STRING_RESPONSE_KEY_NAME];
                node.driverVendor = @"Mai Linh Taxi";
                node.driverLicense = @"123456";
                node.driverCapacity = @"4 seats";
                
                NSMutableArray *loc = [obj objectForKey:STRING_RESPONSE_KEY_LOC];
                CLLocationCoordinate2D coordinateLoc;
                if (loc.count > 0) {
                    coordinateLoc.longitude = ((NSNumber *)[loc objectAtIndex:0]).floatValue;
                    coordinateLoc.latitude = ((NSNumber *)[loc objectAtIndex:1]).floatValue;
                }
                else {
                    coordinateLoc.latitude = STRING_LOCATION_LATITUDE_DEFAULT.floatValue;
                    coordinateLoc.longitude = STRING_LOCATION_LONGTITUDE_DEFAULT.floatValue;
                }
                
                node.coordinate = coordinateLoc;
                [[PersonDataManager clientShared] addNode:node];
            }
        }
        
        [self loadInterface];
    }
    else if (type == ENUM_API_REQUEST_TYPE_CLIENT_CHARGE_BILL) {
        [[AppViewController Shared] hidePopupWithNotificationType:type];
        
        [UserDataManager Shared].selectedPersonID = nil;
        _selectedDriver = nil;
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
        [[UserDataManager Shared] save];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    NSLog(@" requestFailed %@ ", request.responseString);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:type andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable]) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

#pragma mark - TouchedGestureRecognizerProtocol
- (void)touchesOneClickCallback:(NSSet *)touches withEvent:(UIEvent *)event {
    if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_PickUpThisDriver) {
        [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
        [[UserDataManager Shared] save];
        
        [self loadDriverInterfaceWithNodeData:nil];
    }
}

#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if ([view.annotation isKindOfClass:[MKUserLocation class]]) return;
    
    if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_Invalid) {
        _selectedDriver = (PersonNodeData *)view.annotation;
        [UserDataManager Shared].selectedPersonID = _selectedDriver.personID;
        [[UserDataManager Shared] save];
        
        [self loadDriverInterfaceWithNodeData:_selectedDriver];
    }
}

- (void)mapView:(MKMapView *)map regionDidChangeAnimated:(BOOL)animated
{
    
}

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]]) return nil;
    
    static NSString *AnnotationViewID = @"LocationAnnotationViewID";
    
    AIGOMapAnnotationView *annotationView =
    (AIGOMapAnnotationView *)[_mapViewClient dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil)
    {
        annotationView = [[AIGOMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID andDelegate:self];
        
        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [rightButton addTarget:self
                        action:nil
              forControlEvents:UIControlEventTouchUpInside];
        annotationView.rightCalloutAccessoryView = rightButton;
        
        UIImageView *sfIconView = [[UIImageView alloc] initWithImage:IMG_DRIVER_01_PIN];
        sfIconView.frame = CGRectMake(0, 0, IMG_DRIVER_01_PIN.size.width*2/3, IMG_DRIVER_01_PIN.size.height*2/3);
        annotationView.leftCalloutAccessoryView = sfIconView;
        
        annotationView.canShowCallout = YES;
    }
    
    [annotationView loadInterfaceWithAnotation:annotation andImage:IMG_DRIVER_01_PIN];
    
    return annotationView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if ([view.annotation isKindOfClass:[MKUserLocation class]]) return;
    
    _selectedDriver = (PersonNodeData *)view.annotation;
    
    [self loadDriverInterfaceWithNodeData:_selectedDriver];
}

#pragma mark - Remote Notification
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo andNotificationType:(enumRemoveNotificationType)type
{
    NSLog(@"didReceiveRemoteNotification: %i", type);
    
    [self touchUpInsideHideList:nil];
    
    _remoteNotification = (NSMutableDictionary *)userInfo;
    
    switch (type) {
        case enumRemoveNotificationType_DriverAcceptTheRequest:
        {
            if ([UserDataManager Shared].userRequestStatus == enumClientMainStatus_RequestClosestDriver || [UserDataManager Shared].userRequestStatus == enumClientMainStatus_RequestThisDriver) {
                [[AppViewController Shared] showPopupWithNotificationType:type andRemoteNotification:userInfo andDelegate:self];
                
                [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
                
                [UserDataManager Shared].userRequestStatus = enumClientMainStatus_WaitingForDriverArrival;
                [[UserDataManager Shared] save];
            }
            break;
        }
        case enumRemoveNotificationType_DriverNotifyYourArrivalClientPopup:
        {
            [[AppViewController Shared] showPopupWithNotificationType:type andRemoteNotification:userInfo andDelegate:self];
            
            [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
            
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_GettingCar;
            [[UserDataManager Shared] save];
            break;
        }
        case enumRemoveNotificationType_CancelThisTransation:
        {
            [[AppViewController Shared] showPopupWithNotificationType:type andRemoteNotification:userInfo andDelegate:self];
            
            [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
            
            if (_selectedDriver) {
                [UserDataManager Shared].userRequestStatus = enumClientMainStatus_PickUpThisDriver;
            }
            else {
                [UserDataManager Shared].userRequestStatus = enumClientMainStatus_Invalid;
            }
            [[UserDataManager Shared] save];
            break;
        }
        case enumRemoveNotificationType_DriverSendBill:
        {
            [[AppViewController Shared] showPopupWithNotificationType:enumRemoveNotificationType_ClientReceiveBillPopup andRemoteNotification:userInfo andDelegate:self];
            
            [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
            
            [UserDataManager Shared].userRequestStatus = enumClientMainStatus_FinishTrip;
            [[UserDataManager Shared] save];
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - RequestPopupViewDelegate

- (void)touchUpInsideOKRequestPopupCallbackWithNotificationType:(enumRemoveNotificationType)type {
    if (type == enumRemoveNotificationType_DriverAcceptTheRequest) {
        [[AppViewController Shared] hidePopupWithNotificationType:type];
    }
    else if (type == enumRemoveNotificationType_DriverNotifyYourArrivalClientPopup) {
        [[AppViewController Shared] showPopupWithNotificationType:enumRemoveNotificationType_ClientCountDownPopup andRemoteNotification:nil andDelegate:self];
    }
    else {
        [[AppViewController Shared] hidePopupWithNotificationType:type];
    }
}

- (void)touchUpInsideChargeRequestPopupCallbackWithNotificationType:(enumRemoveNotificationType)type {
    [self requestAPIWithType:ENUM_API_REQUEST_TYPE_CLIENT_CHARGE_BILL];
}

- (void)touchUpInsideCashRequestPopupCallbackWithNotificationType:(enumRemoveNotificationType)type {
    [[AppViewController Shared] hidePopupWithNotificationType:type];
}

@end
